package com.xieyong.leetcode;

public class Leetcode135 {
    public static void main(String[] args) {
        Leetcode135 leetcode = new Leetcode135();
        int[] cand = {1,3,4,5,2};
        int candy = leetcode.candy(cand);
        System.out.println(candy);
    }

    public int candy(int[] ratings) {
        int n = ratings.length;
        int[] list = new int[n];
        list[0] = 1;
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                list[i] = list[i - 1] + 1;
            } else {
                list[i] = 1;
            }
        }
        for (int j = n - 2; j >= 0; j--) {
            if(ratings[j] > ratings[j + 1]){
                list[j] = Math.max(list[j], list[j + 1] + 1);
            }
        }
//        for(int i: list){
//            System.out.print(i + ",");
//        }
//        System.out.println();
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += list[i];
        }
        return res;
    }

//      方法通过，简化了逻辑，只需两次遍历就行了其实
//    public int candy(int[] ratings) {
//        int n = ratings.length;
//        int[] list = new int[n];
//        list[0] = 1;
//        for (int i = 1; i < n; i++) {
//            if(ratings[i] > ratings[i - 1]){
//                list[i] = list[i - 1] + 1;
//            } else if(ratings[i] < ratings[i - 1]) {
//                list[i] = 1;
////                当前数小于前一个数时，回去把前一个数加一
//                addbefore(ratings, list, i);
//            } else {
//                list[i] = 1;
//            }
//        }
////        for(int i: list){
////            System.out.print(i + ",");
////        }
////        System.out.println();
//        int res = 0;
//        for (int i = 0; i < n; i++) {
//            res += list[i];
//        }
//        return res;
//    }
//
//    private void addbefore(int[] ratings, int[] list, int i) {
//        for (int j = i - 1; j >= 0; j--) {
//            if(ratings[j] > ratings[j + 1]){
//                list[j] = Math.max(list[j], list[j + 1] + 1);
//            } else {
//                break;
//            }
//        }
//    }
}
